﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace PreContractWeb
{
    public class EmailScheduler
    {
        private static System.Timers.Timer _Timer = null;
        private static bool _isRunning = false;
        //private static ArrayList _TaskList = null;

        public static bool isRunning
        {
            get { return EmailScheduler._isRunning; }
        }

        public static void Start()
        {
            if (_Timer != null)
            {
                _Timer.Stop();
            }
            else
            {
                _Timer = new System.Timers.Timer();
                _Timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
                _Timer.AutoReset = true;
            }
            _Timer.Interval = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ScheduleInterval"]) * 1000;//ms

            // get task list
            //_TaskList = Task.GetTaskList();
            //if (_TaskList.Count > 0)
            //{	// start timer
                _Timer.Start();
                _isRunning = true;
            //}

        }
        public static void Stop()
        {
            _Timer.Stop();
            _isRunning = false;
        }

        private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //Check and schedule
                //Task task;
                //for (int i = 0; i < _TaskList.Count; i++)
                //{
                //    task = (Task)_TaskList[i];
                //    task.Run();
                //}

                // string test = string.Empty;

                SendEmails();

                
            }
            catch(Exception ex)
            {
                BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.SendEmail, "SendEmail:" + ex.Message, "System");
            }
        }

        protected  static void SendEmails()
        {
            DataTable dtPreContractList = null;
            BEGDC.PreContract.BLL.IEmail iEmail = (BEGDC.PreContract.BLL.IEmail)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Email_Service];

            BEGDC.PreContract.DAL.Email email = new BEGDC.PreContract.DAL.Email();

            try
            {

                string sender = System.Configuration.ConfigurationManager.AppSettings["EmailSender"];
                bool emailenabled = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["EmailEnabled"]);


                #region SendtoPrincipal
                DataTable dtEmailPrincipal = iEmail.GetEmailPrincipal();

                for (int i = 0; i < dtEmailPrincipal.Rows.Count; i++)
                {
                    if (dtEmailPrincipal.Rows[i]["PrincipalEmail"].ToString() == null || dtEmailPrincipal.Rows[i]["PrincipalEmail"].ToString() == String.Empty)
                        continue;

                    dtPreContractList = iEmail.GetEmailPreContractListPrincipal(dtEmailPrincipal.Rows[i]["PrincipalEmail"].ToString(),
                                                   dtEmailPrincipal.Rows[i]["Subject"].ToString(), dtEmailPrincipal.Rows[i]["EmailContent"].ToString());

                    string ids = String.Empty;

                    for (int t = 0; t < dtPreContractList.Rows.Count; t++)
                    {
                        ids += (dtPreContractList.Rows[t]["PreContractID"].ToString() + ",");
                    }

                    if (ids == null || ids == String.Empty)
                        continue;

                    string emailContent = BaseFunction.CreateEmail(ids, dtEmailPrincipal.Rows[i]["Principal"].ToString(), dtEmailPrincipal.Rows[i]["EmailContent"].ToString());

                    string principalemail = dtEmailPrincipal.Rows[i]["PrincipalEmail"].ToString();
                    if (!emailenabled)
                        principalemail = sender;

                    BaseFunction.SendMail(principalemail, string.Empty, sender,
                        dtEmailPrincipal.Rows[i]["Subject"].ToString(),emailContent);
                }
                #endregion

                #region SendtoApplicant
                DataTable dtEmailMain = iEmail.GetEmailApplicant();

                for (int i = 0; i < dtEmailMain.Rows.Count; i++)
                {
                    //if (dtEmailMain.Rows[i]["ApplicantEmail"].ToString() == null || dtEmailMain.Rows[i]["ApplicantEmail"].ToString() == String.Empty)
                    //    continue;

                    dtPreContractList = iEmail.GetEmailPreContractList(dtEmailMain.Rows[i]["ApplicantEmail"].ToString(),
                                                   dtEmailMain.Rows[i]["Subject"].ToString(), dtEmailMain.Rows[i]["EmailContent"].ToString());

                    string ids = String.Empty;

                    for (int t = 0; t < dtPreContractList.Rows.Count; t++)
                    {
                        ids += (dtPreContractList.Rows[t]["PreContractID"].ToString() + ",");
                    }

                    if (ids == null || ids == String.Empty)
                        continue;


                    string emailContent = BaseFunction.CreateEmail(ids, dtEmailMain.Rows[i]["Applicant"].ToString(), dtEmailMain.Rows[i]["EmailContent"].ToString());

                    string applicantemail = dtEmailMain.Rows[i]["ApplicantEmail"].ToString();
                    if (!emailenabled)
                        applicantemail = sender;

                    if (applicantemail != string.Empty)
                        BaseFunction.SendMail(applicantemail, string.Empty, sender,
                            dtEmailMain.Rows[i]["Subject"].ToString(),emailContent);

                    for (int z = 0; z < dtPreContractList.Rows.Count; z++)
                    {
                        email = iEmail.GetEmail(Convert.ToInt32(dtPreContractList.Rows[z]["EmailID"].ToString()));
                        email.IsSend = true;
                        email.SendTime = DateTime.Now;
                        email.Update();
                    }

                }
                #endregion
                DateTime starttime =Convert.ToDateTime( System.DateTime.Now.ToString("yyyy-MM-dd") + " " +  "10:00");

                if (System.DateTime.Now.AddSeconds(Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ScheduleInterval"])) > starttime
                    && System.DateTime.Now < starttime)
                {
                    BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.SendEmail, "SendEmail successful.", "System");
                }
            }
            catch (Exception ex)
            {
                if (dtPreContractList != null)
                {
                    for (int z = 0; z < dtPreContractList.Rows.Count; z++)
                    {
                        email = iEmail.GetEmail(Convert.ToInt32(dtPreContractList.Rows[z]["EmailID"].ToString()));
                        email.IsSend = true;
                        email.SendTime = DateTime.Now;
                        email.Update();
                    }
                }


                BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.SendEmail, "SendEmail:" + ex.Message, "System");
                throw ex;
            }
        }
    }
}
